package com.logic.landseaserver.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.logic.common.exception.BusinessException;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.domain.Expand;
import com.logic.landseaserver.domain.ProLine;
import com.logic.landseaserver.domain.ProductLine;
import com.logic.landseaserver.persistence.read.ProductLineReadMapper;
import com.logic.landseaserver.persistence.write.ProductLineWriteMapper;
import com.logic.landseaserver.service.IProductLineService;
import com.logic.landseaserver.ws.dto.ProductLine4TypeDTO;
import com.logic.landseaserver.ws.dto.ProductLineDTO;
import com.logic.system.domain.Configuration;
import com.logic.system.domain.SystemFile;
import com.logic.system.persistence.read.ConfigurationReadMapper;
import com.logic.system.service.impl.FileService;


/**
 * @Author: jack
 * @Date: 2017/5/9
 * @Description: 产品系列接口实现类
 */
@Service
public class ProductLineServiceImpl implements IProductLineService, EnvironmentAware{

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Autowired
	private ProductLineReadMapper productLineReadMapper;
	
	@Autowired
	private ProductLineWriteMapper productLineWriteMapper;
	
	@Autowired
	private ConfigurationReadMapper configReadMapper;
	
    @Autowired
    private FileService fileService;
    
	private static final String ENV_FILE_PATH = "logic.file.path.";
	private static final String LOCAL_PATH = "local";
	private static final String REMOTE_PATH = "remote";

	private static RelaxedPropertyResolver propertyResolver;
	
	@Override
	public void setEnvironment(Environment environment) {
		propertyResolver = new RelaxedPropertyResolver(environment, ENV_FILE_PATH);
	}
	
	public String getUrl(String nameStr,String pathStr){
		String path = propertyResolver.getProperty(LOCAL_PATH, String.class, null);
		StringBuffer url = propertyResolver.getProperty(REMOTE_PATH, StringBuffer.class, null);

		url.append("/");
		if(pathStr != null && !"".equals(pathStr)) {
			url.append(pathStr).append("/");
		}
		url.append(nameStr);
		
		return url.toString();
	}
	
	
	@Override
	public void delete(String arg0) throws BusinessException {
	}

	@Override
	public int insertProductLine(ProductLineDTO productLineDTO) throws BusinessException {
		int productLineInt = -1;
		if (validateForInsert(productLineDTO)) 
		{//需补充验证
			ProductLine productLine = new ProductLine(); 
			int orderId;
			setPrLiByPrLiDTO(productLine,productLineDTO);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			Date date=new Date();
			productLine.setCreatedBy(productLineDTO.getUserId());
			productLine.setCreatedDtm(date);
			productLine.setLastModifiedBy(productLineDTO.getUserId());
			productLine.setLastModifiedDtm(date);
			productLineWriteMapper.insertSelective(productLine);
		}
		return productLineInt;
	}

	@Override
	public List<ProductLineDTO> query(QueryUtil queryUtil) {
		List<ProductLineDTO> result = productLineReadMapper.getProductLineDTOList(queryUtil);
		return result;
	}

	@Override
	public Boolean validateForInsert(Object arg0) throws BusinessException {
		return Boolean.valueOf(true);
	}
	
	//通过orderDTO创建order
	public void setPrLiByPrLiDTO(ProductLine productLine ,ProductLineDTO productLineDTO){
		if(!StringUtils.isEmpty(productLineDTO.getSerial()))
		{
			productLine.setSerial(productLineDTO.getSerial());
		}
		if(!StringUtils.isEmpty(productLineDTO.getTitle()))
		{
			productLine.setTitle(productLineDTO.getTitle());
		}
		if(!StringUtils.isEmpty(productLineDTO.getDescription()))
		{
			productLine.setDescription(productLineDTO.getDescription());
		}
		if(!StringUtils.isEmpty(productLineDTO.getImage()))
		{
			productLine.setImage(productLineDTO.getImage());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getKeyword()))
		{
			productLine.setKeyword(productLineDTO.getKeyword());
		}
		if(!StringUtils.isEmpty(productLineDTO.getPublicSpace()))
		{
			productLine.setPublicSpace(productLineDTO.getPublicSpace());
		}
		if(!StringUtils.isEmpty(productLineDTO.getLivingSpace()))
		{
			productLine.setLivingSpace(productLineDTO.getLivingSpace());
		}
		
		if(!StringUtils.isEmpty(productLineDTO.getExpand1Title()))
		{
			productLine.setExpand1Title(productLineDTO.getExpand1Title());
		}
		if(!StringUtils.isEmpty(productLineDTO.getExpand1Attribute()))
		{
			productLine.setExpand1Attribute(productLineDTO.getExpand1Attribute());
		}
		
		if(!StringUtils.isEmpty(productLineDTO.getExpand2Title()))
		{
			productLine.setExpand2Title(productLineDTO.getExpand2Title());
		}
		if(!StringUtils.isEmpty(productLineDTO.getExpand2Attribute()))
		{
			productLine.setExpand2Attribute(productLineDTO.getExpand2Attribute());
		}
		
		if(!StringUtils.isEmpty(productLineDTO.getExpand3Title()))
		{
			productLine.setExpand3Title(productLineDTO.getExpand3Title());
		}
		if(!StringUtils.isEmpty(productLineDTO.getExpand3Attribute()))
		{
			productLine.setExpand3Attribute(productLineDTO.getExpand3Attribute());
		}
		
		if(!StringUtils.isEmpty(productLineDTO.getExpand4Title()))
		{
			productLine.setExpand4Title(productLineDTO.getExpand4Title());
		}
		if(!StringUtils.isEmpty(productLineDTO.getExpand4Attribute()))
		{
			productLine.setExpand4Attribute(productLineDTO.getExpand4Attribute());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getProType()))
		{
			productLine.setProType(productLineDTO.getProType());
		}
		if(!StringUtils.isEmpty(productLineDTO.getCreatedDtm()))
		{
			productLine.setCreatedDtm(productLineDTO.getCreatedDtm());
		}
		if(!StringUtils.isEmpty(productLineDTO.getCreatedBy()))
		{
			productLine.setCreatedBy(productLineDTO.getCreatedBy());
		}
		if(!StringUtils.isEmpty(productLineDTO.getLastModifiedDtm()))
		{
			productLine.setLastModifiedDtm(productLineDTO.getLastModifiedDtm());
		}
		if(!StringUtils.isEmpty(productLineDTO.getLastModifiedBy()))
		{
			productLine.setLastModifiedBy(productLineDTO.getLastModifiedBy());
		}
		if(!StringUtils.isEmpty(productLineDTO.getVersion()))
		{
			productLine.setVersion(productLineDTO.getVersion());
		}
		if(!StringUtils.isEmpty(productLineDTO.getDeleted()))
		{
			productLine.setDeleted(productLineDTO.getDeleted());
		}
	}
	
	@Override
	public void editProductLine(ProductLineDTO productLineDTO) throws BusinessException {
		ProductLine productLine = productLineReadMapper.selectByPrimaryKey(productLineDTO.getId());
		setPrLiByPrLiDTO(productLine,productLineDTO);
		productLine.setLastModifiedBy(productLineDTO.getUserId());
		productLine.setLastModifiedDtm(new Date());
		productLineWriteMapper.updateByPrimaryKeySelective(productLine);
	}

	@Override
	public void deleteProductLine(Integer id) throws BusinessException {
		ProductLine productLine = new ProductLine(); 
		productLine.setId(id);
		//activityWriteMapper.deleteByPrimaryKey(id);
		productLine.setLastModifiedBy(1);//假设当前操作管理员id为1
		productLine.setLastModifiedDtm(new Date());
		productLine.setDeleted(true);
		productLineWriteMapper.updateByPrimaryKeySelective(productLine);
	}

	@Override
	public Object get(Integer arg0) throws BusinessException {
		return null;
	}
	@Override
	public int insert(Object arg0) throws BusinessException {
		return 0;
	}
	@Override
	public void update(Object arg0) throws BusinessException {
	}
	@Override
	public Boolean validate(Object arg0) throws BusinessException {
		return null;
	}
	@Override
	public Boolean validateForDelete(Object arg0) throws BusinessException {
		return null;
	}
	
	@Override
	public Boolean validateForUpdate(Object arg0) throws BusinessException {
		return null;
	}
	@Override
	public String getValueByCode(String code) throws BusinessException {
		return null;
	}
	
	@Override
	public List<ProLine> getProductLineAll() throws BusinessException{
		List<ProLine>  pro1 = new ArrayList<ProLine>();
		List<ProLine>  pro = productLineReadMapper.getProductLineAll();
		for(int j=0;j<pro.size();j++){
			ProLine pl = (ProLine)pro.get(j);
			SystemFile  img = (SystemFile)fileService.get(pl.getImage());
			if (null != img && null != img.getFullPath()) 
			{
				pl.setPath(img.getFullPath());
			}
			
			pro1.add(pl);
		}
		return pro1;
	}
	
	
	
	private String getUrl(String str) throws BusinessException {
		StringBuffer url = propertyResolver.getProperty(REMOTE_PATH, StringBuffer.class, null);
		String urlStr = url.toString();
//		urlStr = urlStr.substring(0, urlStr.indexOf("/u"));
//		if(urlStr.indexOf("/u")>=0){
//            urlStr = urlStr.substring(0, urlStr.indexOf("/u"));
//        }
		urlStr = urlStr + str;
		return urlStr;
	}
	
	//循环获取icon图片信息
	public List<Expand> getExpand(String str1) throws BusinessException{
//		String str = "PRL1,PRL2,PRL3";
		List<Expand>  pro1 = new ArrayList<Expand>();
        String[] s = str1.split(",");
		for(int j=0;j<s.length;j++){
			Configuration config= configReadMapper.selectByPrimaryKey(s[j].toString());
			Expand ex = new Expand();
			ex.setName(config.getDescription());
			ex.setPath(this.getUrl(config.getValue()));
			pro1.add(ex);
		}
		return pro1;
	}

	@Override
	public List<ProductLine4TypeDTO> getProductLineListForFlag(String flag) throws BusinessException{
		List<ProductLine4TypeDTO> pubRes =new ArrayList<ProductLine4TypeDTO>();
		String [] s1 = flag.split(",");
		List ar = new ArrayList();
		for(int i=0;i<s1.length;i++){
			ar.add(s1[i]);
		}
		
		List<ProductLineDTO> result = productLineReadMapper.getProductLineForFlag(ar);
		for(int i=0;i<result.size();i++)
		{
			
			ProductLine4TypeDTO pdto = new ProductLine4TypeDTO();
			ProductLineDTO act = result.get(i);
			pdto.setId(act.getId());
			pdto.setUserId(act.getUserId());
			pdto.setSerial(act.getSerial());
			pdto.setTitle(act.getTitle());
			pdto.setDescription(act.getDescription());
			pdto.setImage(act.getImage());
			pdto.setProType(act.getProType());
			pdto.setKeyword(act.getKeyword());
			
			//获取公共空间图片路径   
			List<SystemFile> detailImgs1 = new ArrayList<>();
			if(null != act.getPublicSpace() && !"".equals(act.getPublicSpace()))
//		    if(!StringUtils.isEmpty(act.getPublicSpace()))
		    {
			    try {
					for(String imgid1 : act.getPublicSpace().split(",")){
			            SystemFile  img1 = (SystemFile)fileService.get(imgid1);
						detailImgs1.add(img1);
			        }
					pdto.setPublicSpace(detailImgs1);
			    } catch (BusinessException e) {
			        logger.error("getProductLineListForFlag error.", e);
				}
		    }
			 //获取居住空间图片路径   
			List<SystemFile> detailImgs2 = new ArrayList<>();
			if(null != act.getLivingSpace() && !"".equals(act.getLivingSpace()))
//		    if(!StringUtils.isEmpty(act.getLivingSpace()))
		    {
			    try {
					for(String imgid2 : act.getLivingSpace().split(","))
					{
			            SystemFile  img2 = (SystemFile)fileService.get(imgid2);
						detailImgs2.add(img2);
			        }
					pdto.setLivingSpace(detailImgs2);
			    } catch (BusinessException e) {
			        logger.error("getProductLineListForFlag error.", e);
				}
		    }
			
			pdto.setExpand1Title(act.getExpand1Title());
			if(!StringUtils.isEmpty(act.getExpand1Attribute())){
				pdto.setExpand1Attribute(this.getExpand(act.getExpand1Attribute()));
			}
			pdto.setExpand2Title(act.getExpand2Title());
			if(!StringUtils.isEmpty(act.getExpand2Attribute())){
				pdto.setExpand2Attribute(this.getExpand(act.getExpand2Attribute()));
			}
			pdto.setExpand3Title(act.getExpand3Title());
			if(!StringUtils.isEmpty(act.getExpand3Attribute())){
				pdto.setExpand3Attribute(this.getExpand(act.getExpand3Attribute()));
			}
			pdto.setExpand4Title(act.getExpand4Title());
			if(!StringUtils.isEmpty(act.getExpand4Attribute())){
				pdto.setExpand4Attribute(this.getExpand(act.getExpand4Attribute()));
			}

			pdto.setCreatedDtm(act.getCreatedDtm());
			pdto.setCreatedBy(act.getCreatedBy());
			pdto.setLastModifiedDtm(act.getLastModifiedDtm());
			pdto.setLastModifiedBy(act.getLastModifiedBy());
			pdto.setVersion(act.getVersion());
			pdto.setDeleted(act.getDeleted());
			pdto.setCodedesczh(act.getCodedesczh());
		    List<SystemFile> detailImgs = new ArrayList<>();
		    if(null != act.getImage() && !"".equals(act.getImage()))
//		    if(!StringUtils.isEmpty(act.getImage()))
		    {
			    try {
					for(String imgid : act.getImage().split(",")){
			            SystemFile  img = (SystemFile)fileService.get(imgid);
						detailImgs.add(img);
			        }
					pdto.setImgs(detailImgs);
				    pubRes.add(pdto);
			    } catch (BusinessException e) {
			        logger.error("getProductLineListForFlag error.", e);
				}
		    }
		}
        
		return pubRes;
	}
	

}
